/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.repository.dao;

import com.alibaba.csp.sentinel.dashboard.rule.database.enums.DatabaseRuleEnums;
import com.alibaba.csp.sentinel.dashboard.repository.rule.InMemoryRuleRepositoryAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.swing.table.DefaultTableModel;


/**
 *
 */
@Component
public class InitDBToMemConfig {
    @Autowired
    ApplicationContext context;
    //初始化数据库数据到内存中
    @PostConstruct
    public void initMemoryData() {
        SqlHelper.setDbConfig(context.getBean(DbConfig.class));
        DefaultTableModel resultSet = SqlHelper.getResultSet("SELECT `content`,`rule_type` FROM   `cc_sentinel_rule`");
        try {
            for (int i = 0; i < resultSet.getRowCount(); i++) {
                String content = resultSet.getValueAt(i, 0).toString();
                int ruleType = (int) resultSet.getValueAt(i, 1);
                DatabaseRuleEnums ruleEnums = DatabaseRuleEnums.convert(ruleType);
                InMemoryRuleRepositoryAdapter ruleStore = (InMemoryRuleRepositoryAdapter) context.getBean(ruleEnums.getBeanName());
                if (ruleStore != null)
                    ruleStore.save(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
